package com.mymusic;

import java.io.IOException;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;


public class AlbumArt extends Activity implements SeekBar.OnSeekBarChangeListener {
	String[] trackData;
	String[] tracks;
	//String[] albumIds;

	Object[] objArray;
	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	private LinearLayout linearLayout;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	MediaPlayer mp =new MediaPlayer();
	private int selectedTrackIndex = 0; 
	private Utilities utils;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;
	//ArrayList<HashMap<String, Track>> albumTracks ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		songTitleLabel= (TextView) findViewById(R.id.songTitle);
		songTitleLabel.setText((CharSequence) getIntent().getExtras().get("Title"));
		 objArray=(Object[]) getIntent().getExtras().get("albumTracks");
		//albumTracks=     
		selectedTrackIndex=(Integer) getIntent().getExtras().get("position");
		// All player buttons
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnForward = (ImageButton) findViewById(R.id.btnForward);
		btnBackward = (ImageButton) findViewById(R.id.btnBackward);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
		btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
		linearLayout=(LinearLayout) findViewById(R.id.songThumbnail);
		
		playSong( selectedTrackIndex);
		utils = new Utilities(); 
		
		  
        //Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
        //Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri,albumTracks[0].getAlbumId());
        
		
		/**
		 * Play button click event
		 * plays a song and changes button to pause image
		 * pauses a song and changes button to play image
		 * */
		btnPlay.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// check for already playing
				if(mp.isPlaying()){
					if(mp!=null){
						mp.pause();
						// Changing button image to play button
						btnPlay.setImageResource(R.drawable.btn_play);
					}
				}else{
					// Resume song
					if(mp!=null){
						mp.start();
						// Changing button image to pause button
						btnPlay.setImageResource(R.drawable.btn_pause);
					}
				}
				
			}
		});
		/**
		 * Next button click event
		 * Plays next song by taking currentSongIndex + 1
		 * */
		btnNext.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				 
				// check if next song is there or not
				if(selectedTrackIndex < (objArray.length - 1)){
					playSong(selectedTrackIndex + 1);
					selectedTrackIndex = selectedTrackIndex + 1;
				}else{
					// play first song
					playSong(0);
					selectedTrackIndex = 0;
				}
				 
				
			}
		});
		
		/**
		 * Back button click event
		 * Plays previous song by currentSongIndex - 1
		 * */
		btnPrevious.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(selectedTrackIndex > 0){
					playSong(selectedTrackIndex - 1);
					selectedTrackIndex = selectedTrackIndex - 1;
				}else{
					// play last song
					playSong(objArray.length - 1);
					selectedTrackIndex = objArray.length - 1;
				}
				
			}
		});
		
		/**
		 * Forward button click event
		 * Forwards song specified seconds
		 * */
		btnForward.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// get current song position				
				int currentPosition = mp.getCurrentPosition();
				// check if seekForward time is lesser than song duration
				if(currentPosition + seekForwardTime <= mp.getDuration()){
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				}else{
					// forward to end position
					mp.seekTo(mp.getDuration());
				}
			}
		});
		
		/**
		 * Backward button click event
		 * Backward song to specified seconds
		 * */
		btnBackward.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// get current song position				
				int currentPosition = mp.getCurrentPosition();
				// check if seekBackward time is greater than 0 sec
				if(currentPosition - seekBackwardTime >= 0){
					// forward song
					mp.seekTo(currentPosition - seekBackwardTime);
				}else{
					// backward to starting position
					mp.seekTo(0);
				}
				
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.album_art, menu);
		return true;
	}

	/*private String[] getAudioList(long id) {

		String[] projection = new String[] {
				MediaStore.Audio.Media.DISPLAY_NAME,
				MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM_ID,
				MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
				MediaStore.Audio.Media.TRACK };
		String selection = null;
		String[] selectionArgs = null;
		String sortOrder = MediaStore.Audio.Media.TRACK + " ASC";
		String where = MediaStore.Audio.Media.ALBUM_ID + "=" + id + " AND "
				+ MediaStore.Audio.Media.IS_MUSIC + "=1";
		Cursor mCursor = getContentResolver().query(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, where,
				selectionArgs, sortOrder);

		
		 * final Cursor mCursor =
		 * getContentResolver().query(MediaStore.Audio.Media
		 * .EXTERNAL_CONTENT_URI, new String[] {
		 * MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA },
		 * null, null, "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
		 

		int count = mCursor.getCount();

		 
		trackData = new String[count];
		tracks = new String[count];
		//albumIds = new String[count];
		int i = 0;
		if (mCursor.moveToFirst()) {
			do {
				tracks[i] = mCursor
						.getString(mCursor
								.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
				// tracks[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(
				// MediaStore.Audio.Media.TITLE));
				trackData[i] = mCursor.getString(mCursor
						.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
				//albumIds[i] = mCursor						.getString(mCursor								.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));

				i++;
			} while (mCursor.moveToNext());
		}

		mCursor.close();

		return tracks;
	}
	*/

	private void playSong(int i)  {
		try {
		Track track=(Track) objArray[i];
		Log.d("ringtone", "playSong :: " +track.getTrackTitle());

		mp.reset();
		mp.setDataSource(track.getTrackData());
		// mMediaPlayer.setLooping(true);
		mp.prepare();
		mp.start();
		// Displaying Song title
		 
    	songTitleLabel.setText(track.getTrackTitle());
		
    	// Changing Button Image to pause image
		btnPlay.setImageResource(R.drawable.btn_pause);
		
		// set Progress bar values
		songProgressBar.setProgress(0);
		songProgressBar.setMax(100);
		
		// Updating progress bar
		updateProgressBar();	
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = mp.getDuration();
			   long currentDuration = mp.getCurrentPosition();
			  
			   // Displaying Total Duration time
			   songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
			   
			   // Updating progress bar
			   int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			   songProgressBar.setProgress(progress);
			   
			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};
	
	/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);        
    }

	@Override
	public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
		// remove message Handler from updating progress bar
				mHandler.removeCallbacks(mUpdateTimeTask);
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void onPause() {
		Log.d("PAUSE","PAUSE");
		/*Intent intent = new Intent(this, HomeActivity.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
		
		NotificationManager notificationManager =
				    (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		 Notification	   myNotification = new Notification(R.drawable.ic_launcher,
				     "My Music",
				     System.currentTimeMillis());
				   Context context = getApplicationContext();
				   String notificationTitle = "My Music";
				   String notificationText = ((Track) objArray[selectedTrackIndex]).getTrackTitle();
				   Intent myIntent = new Intent(this, HomeActivity.class);
				   PendingIntent pendingIntent
				     = PendingIntent.getActivity(this,
				       0, myIntent,
				       Intent.FLAG_ACTIVITY_NEW_TASK);
				   myNotification.defaults |= Notification.DEFAULT_SOUND;
				   myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
				   myNotification.setLatestEventInfo(context,
				      notificationTitle,
				      notificationText,
				      pendingIntent);
				   notificationManager.notify(1, myNotification);
				  */
				   
		super.onPause();
	}
	@Override
	protected void onStop() {
		Log.d("onStop","onStop");
		super.onStop();
	}
}
